<template>
  <div ref="chart" style="width: 100%; height: 100%" />
</template>
<script>
export default {
  components: {},
  props: {
    data: {
      type: Array,
      default: function () {
        return [];
      },
    },
    title: {
      type: String,
      default: "",
    },
    options: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  data() {
    return {
      defaultOptions: {
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "10%",
        },
        grid: { y: 15, y2: 20, x: 50, x2: 10 },
        series: [
          {
            type: "pie",
            radius: ["40%", "60%"],
            center: ["50%", "60%"],
            data: [],
            label: {
              normal: {
                show: false,
                position: "inside",
              },
            },
          },
        ],
      },
    };
  },
  watch: {
    data() {
      this.myOptions.series[0].data = this.data;
      this.myChart.setOption(this.myOptions);
    },
  },
  mounted() {
    window.addEventListener("resize", this.resizeHandle);
    this.initChart();
  },
  methods: {
    initChart() {
      this.myChart = this.$echarts.init(this.$refs.chart);
      this.myOptions = this.defaultOptions;
      if (this.options && JSON.stringify(this.options) !== "{}") {
        for (const i in this.options) {
          this.myOptions[i] = this.options[i];
        }
      }
      this.myOptions.series[0].data = this.data;
      if (this.title) {
        this.myOptions.title = {
          text: this.title,
          left: "center",
          textAlign: "auto",
          textStyle: {
            fontSize: "14px",
          },
        };
        this.myOptions.series[0].top = 60;
      }
      this.myChart.setOption(this.myOptions);
      this.myChart.on("click", (params) => {
        this.$emit("click", params);
      });
    },
    resizeHandle() {
      this.myChart.resize();
    },
  },
};
</script>
<style lang="scss" scoped></style>
